package com.cloudcreativity.blyg.utils;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ObservableField;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.LayoutInflater;

import com.cloudcreativity.blyg.R;
import com.cloudcreativity.blyg.base.BaseDialogImpl;
import com.cloudcreativity.blyg.databinding.LayoutDialogChangePwdBinding;
import com.cloudcreativity.blyg.entity.BaseStringResult;
import com.cloudcreativity.blyg.receiver.MyBusinessReceiver;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class ChangePwdUtils extends Dialog {

    public ObservableField<String> old = new ObservableField<>();
    public ObservableField<String> pwd = new ObservableField<>();
    private BaseDialogImpl baseDialog;
    public ChangePwdUtils(@NonNull Context context, BaseDialogImpl baseDialog) {
        super(context, R.style.myProgressDialogStyle);
        this.baseDialog = baseDialog;
        setCancelable(true);
        setCanceledOnTouchOutside(false);
        LayoutDialogChangePwdBinding binding = DataBindingUtil.inflate(LayoutInflater.from(context),
                R.layout.layout_dialog_change_pwd,
                null,false);
        setContentView(binding.getRoot());
        binding.setUtils(this);
    }

    public void onClose(){
        dismiss();
    }

    public void onOk(){
        if(TextUtils.isEmpty(old.get())){
            ToastUtils.showShortToast(getContext(),"旧密码不能为空");
            return;
        }
        if(TextUtils.isEmpty(pwd.get())){
            ToastUtils.showShortToast(getContext(),"新密码不能为空");
            return;
        }
        if(pwd.get().length()<6){
            ToastUtils.showShortToast(getContext(),"新密码不能少于6位");
            return;
        }
        HttpUtils.getInstance().modifyPwd(old.get(),pwd.get())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<BaseStringResult>(baseDialog,true) {
                    @Override
                    public void onSuccess(BaseStringResult t) {
                        ToastUtils.showLongToast(getContext(),"密码修改成功，需要重新登录");
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                KeyBoardHelper.close(getContext(),ChangePwdUtils.this);
                                dismiss();
                                Intent intent = new Intent();
                                intent.setAction(MyBusinessReceiver.ACTION_RE_LOGIN);
                                getContext().sendBroadcast(intent);

                            }
                        },1500);
                    }
                });

    }

}
